package yong.hee;

import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.database.Cursor;
import android.os.Handler;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

/** Custom adapter so we can apply transformations on the data */
public class TwitCursorAdapter extends SimpleCursorAdapter {
	static final String[] from = { DbHelper.C_CREATED_AT,
			DbHelper.C_SCREEN_NAME, DbHelper.C_TEXT_BODY };
	static final int[] to = { R.id.text_created_at, R.id.twit_screen_name,
			R.id.twit_body };
	protected static final int UPDATE_FRIEND_IMAGE = 0;
	Handler mHandler = new Handler();

	public TwitCursorAdapter(Context context, Cursor c) {
		super(context, R.layout.timeline_item, c, from, to);
	}

	@Override
	public void bindView(View row, Context context, Cursor cursor) {
		super.bindView(row, context, cursor);

		long createdAt = cursor.getLong(cursor.getColumnIndex(DbHelper.C_CREATED_AT));
		TextView textCreatedAt = (TextView) row.findViewById(R.id.text_created_at);
		textCreatedAt.setText(DateUtils.getRelativeTimeSpanString(createdAt));

		TextView textRank = (TextView) row.findViewById(R.id.rank);
		textRank.setText(cursor.getPosition());
		
		URL imageURL = null;
		try {
			imageURL = new URL(cursor.getString(cursor.getColumnIndex(DbHelper.C_IMAGE_URL)));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		ImageView friendImage = (ImageView) row.findViewById(R.id.friend_image);
		FriendImageDownloader fid = new FriendImageDownloader(imageURL, friendImage, context, mHandler);
		fid.start();
	}

}
